#coding=utf-8
#LightCam TCP端口监控程序
#init by hfh 20150212

import multiprocessing,subprocess
import socket,os,time,re,traceback,sys
import lc_libs

def func(agent_hostname,portname,definenumber,operator,interval,severity,porttype,schedule,holiday):
	while True:
		try:
			Node=agent_hostname
			AlertGroup="MonitorTcpLink"
			AlertKey=porttype+"-"+portname
			Summary=""
			
			#判断时间策略
			tempflags=lc_libs.lc_schedule(schedule)
			if tempflags==False:
				time.sleep(int(interval))
				continue
			#判断节假日
			holiday_state=0
			if int(holiday)==1:
				if lc_libs.lc_isholiday():
					holiday_state=1
			if holiday_state==1:
				time.sleep(int(interval))
				continue
			#执行端口检查
			comd="netstat -an|grep "+porttype+"|awk '{print $4}'|grep \":"+str(portname)+"$\"|wc -l"
			popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
			#判断子进程是否结束
			while True:
				if popen.poll()==None:
					time.sleep(0.1)
					continue
				else:
					break
			#初始化标志文件
			alertfilename="../alert/lc_tcplink_"+porttype+"_"+portname
			#处理程序
			line=popen.stdout.read().strip("\n").strip("\r")
			res=lc_libs.lc_operator(int(line),operator,int(definenumber))
			if res:
				Severity="1"
				Type="2"
				#Summary="DefineCount:"+definenumber+",RealCount:"+line
				Summary=agent_hostname+"状态为"+porttype+"的"+portname+"端口数量正常,应该为"+definenumber+",实际为"+line
				strs=lc_libs.lc_gen_alert(agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
				print strs
				db.update_eventsdb(events_table,agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
				#logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
				#logfile.write(logdate+" "+strs+"\n")
				#logfile.flush()
			else:
				Severity=severity
				Type="1"
				#Summary="DefineCount:"+definenumber+",RealCount:"+line
				Summary=agent_hostname+"状态为"+porttype+"的"+portname+"端口数量异常,应该为"+definenumber+",实际为"+line
				strs=lc_libs.lc_gen_alert(agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
				print strs
				db.update_eventsdb(events_table,agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
				#logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
				#logfile.write(logdate+" "+strs+"\n")
				#logfile.flush()
			#数据入库
			#hdb.insert_historydb(Node,porttype+"-"+portname,Summary)
			datas=[
				{"Node":Node,"Name":porttype+"-"+portname,"Value":Summary,"Time":int(time.time())}
				]
			db.insertDatas(history_table,datas)
		except Exception:
			excinfo=traceback.format_exc()
			print excinfo
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" :\n"+excinfo+"\n")
			logfile.flush()
			time.sleep(1)
		time.sleep(int(interval))

if __name__ == "__main__":


	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()
	
	agent_hostname=lc_libs.lc_gethostname()
	
	pool = multiprocessing.Pool(processes=1)
	result = []
	
	#初始化events数据库
	#dbfile="../db/lc_events.db"
	#tablename="lc_events"
	#tablefield="Node varchar(32),AlertGroup varchar(64),AlertKey varchar(64),Severity varchar(8),Type varchar(8),LastOccurrence varchar(32),Summary varchar(256)"
	#db=lc_libs.lc_dboperater(dbfile,tablename,tablefield)
	#db.create_db()
	#db.close_db()
	
	#初始化lc_history数据库
	#thismonth=time.strftime('%Y%m',time.localtime())
	#dbfile="../db/lc_history_"+thismonth+".db"
	#dbfile="../db/lc_history.db"
	#tablename="lc_tcplink"
	#tablefield="Node varchar(32),Name varchar(64),Value varchar(64),NTime varchar(32)"
	#hdb=lc_libs.lc_dboperater(dbfile,tablename,tablefield)
	#hdb.create_db()
	#hdb.insert_historydb(Node,Name,Value)



	try:
		#初始化数据库
		
		db=lc_libs.lc_mongodb_operater('127.0.0.1',27017)

		db.connect()
		Conn=db.getConn()
		if Conn==None:
			print "Can not Connect to the MondbDB"
			exit(0)
		
		events_dbname='lc_events'
		events_tablename='lc_events'
		
		history_dbname='lc_history'
		history_tablename="lc_tcplink"
		
		events_db=db.useDatabase(events_dbname)
		events_table=db.UseCollection(events_db,events_tablename)
		
		history_db=db.useDatabase(history_dbname)
		history_table=db.UseCollection(history_db,history_tablename)

	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" 初始化数据库失败:\n"+excinfo+"\n")
		logfile.flush()
		exit(0)



	#主程序
	for line in open(confname):
		#if line[0] == '#' or agent_hostname != line.split("\t")[0]:
		if line[0] == '#' or line.split("\t")[0] not in (agent_hostname,'default'):
			continue
		portname=line.strip('\n').split("\t")[1]
		definenumber=line.strip('\n').split("\t")[2]
		operator=line.strip('\n').split("\t")[3]
		interval=line.strip('\n').split("\t")[4]
		severity=line.strip('\n').split("\t")[5]
		porttype=line.strip('\n').split("\t")[6]
		schedule=line.strip('\n').split("\t")[7]
		holiday=line.strip('\n').split("\t")[8]
		
		pool = multiprocessing.Pool(processes=1)
		result.append(pool.apply_async(func, (agent_hostname,portname,definenumber,operator,interval,severity,porttype,schedule,holiday)))

	pool.close()
	pool.join()
	print result
